import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject

class RadioList(Gtk.ScrolledWindow):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        
        # Tree view
        self.tree_view = Gtk.TreeView()
        self.add(self.tree_view)
        
        # Model
        self.list_store = Gtk.ListStore(str, str, str, object)  # id, name, category, station
        self.tree_view.set_model(self.list_store)
        
        # Columns
        renderer = Gtk.CellRendererText()
        
        column = Gtk.TreeViewColumn("Name", renderer, text=1)
        column.set_sort_column_id(1)
        self.tree_view.append_column(column)
        
        column = Gtk.TreeViewColumn("Category", renderer, text=2)
        column.set_sort_column_id(2)
        self.tree_view.append_column(column)
        
        # Load data
        self._load_data()
        
        # Selection
        self.selection = self.tree_view.get_selection()
        self.selection.connect("changed", self._on_selection_changed)
    
    def _load_data(self):
        self.list_store.clear()
        for category in self.app.radio_manager.categories:
            stations = self.app.radio_manager.get_stations_by_category(category['id'])
            for station in stations:
                self.list_store.append([
                    station['id'],
                    station['name'],
                    category['name'],
                    station
                ])
    
    def _on_selection_changed(self, selection):
        model, treeiter = selection.get_selected()
        if treeiter:
            station = model[treeiter][3]
            # Update details view or other UI elements
    
    def get_selected_station(self):
        model, treeiter = self.selection.get_selected()
        if treeiter:
            return model[treeiter][3]
        return None